package com.kiell.gulimall.ware.service.impl;

import com.kiell.common.constant.WareConstant;
import com.kiell.gulimall.ware.entity.PurchaseDetailEntity;
import com.kiell.gulimall.ware.service.PurchaseDetailService;
import com.kiell.gulimall.ware.service.WareSkuService;
import com.kiell.gulimall.ware.vo.MergeVo;
import com.kiell.gulimall.ware.vo.PurchaseDoneVo;
import com.kiell.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiell.common.utils.PageUtils;
import com.kiell.common.utils.Query;

import com.kiell.gulimall.ware.dao.PurchaseDao;
import com.kiell.gulimall.ware.entity.PurchaseEntity;
import com.kiell.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单：01新创建及未领取的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0).or().eq("status",1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /** 合并采购单
     * @param mergeVo
     * @return
     */
    @Transactional
    @Override
    public Integer mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //不存在已有采购单
        if (purchaseId == null){
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();

        }
        //确认才采购项状态是0或1才可以合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> canBeMergeDetails = purchaseDetailService.listByIds(items);
        //更新已合并采购单状态
        List<PurchaseDetailEntity> detailEntities = canBeMergeDetails.stream().filter(i->i.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()||
                i.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                         .map(m -> {
                             Long mPurchaseId = m.getPurchaseId();
                             if (mPurchaseId != null){
                                 //已被分配过的需要将原来的采购单金额减去
                                 PurchaseEntity byId = this.getById(mPurchaseId);
                                 byId.setAmount(byId.getAmount().subtract(m.getSkuPrice()));
                                 byId.setUpdateTime(new Date());
                                 this.updateById(byId);
                             }
                             //更新已合并采购单状态
                             PurchaseDetailEntity detail = new PurchaseDetailEntity();
                             detail.setId(m.getId());
                             detail.setPurchaseId(finalPurchaseId);
                             detail.setSkuPrice(m.getSkuPrice());
                             detail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                             return detail;
                         }).collect(Collectors.toList());;

//        List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
//            //更新已合并采购单状态
//            PurchaseDetailEntity detail = new PurchaseDetailEntity();
//            detail.setId(i);
//            detail.setPurchaseId(finalPurchaseId);
//            detail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
//            return detail;
//        }).collect(Collectors.toList());
        boolean result = purchaseDetailService.updateBatchById(detailEntities);

        BigDecimal purchaseCountPrice = detailEntities
                .stream()
                .map(PurchaseDetailEntity::getSkuPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        PurchaseEntity updateTime = new PurchaseEntity();
        updateTime.setAmount(purchaseCountPrice);
        updateTime.setId(purchaseId);
        updateTime.setUpdateTime(new Date());
        this.updateById(updateTime);

        return result ?1:0;
    }

    /** 被分配人员领取采购单
     * @param ids
     * @return
     */
    @Override
    public int received(List<Long> ids) {
        //1.确认当前采购单是新建或已分配状态
        List<PurchaseEntity> list = ids.stream().map(id -> {
                                   PurchaseEntity byId = this.getById(id);
                                   return byId;
                               })
                               .filter(item -> {
                                   if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                                           item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                                       return true;
                                   }
                                   return false;
                               })
                               .map(item -> {
                                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                                    return item;
                }).collect(Collectors.toList());
        //2.改变采购单的状态
        boolean b = this.updateBatchById(list);
        //3.改变采购项的状态
        list.forEach(item->{
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetaileByPurchaseId(item.getId());
            List<PurchaseDetailEntity> updates = detailEntities.stream().map(entity -> {
                PurchaseDetailEntity detail = new PurchaseDetailEntity();
                detail.setId(entity.getId());
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(updates);
        });
        return b ? 1:0;
    }

    /**
     * @param doneVo
     * @return
     */
    @Override
    public int done(PurchaseDoneVo doneVo) {

        //2.改变每个采购项状态
        boolean isItemAllDone = true;

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        for (PurchaseItemDoneVo item :items){
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            PurchaseDetailEntity detailById = purchaseDetailService.getById(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){

                isItemAllDone = false;
                detail.setStatus(item.getStatus());

                Integer skuNum = item.getSkuNum();
                Integer finalSkuNum  = 0;
                detail.setReason(item.getReason());
                if (skuNum != null){
                    if (detailById != null){
                        finalSkuNum = detailById.getSkuNum() - skuNum;
                        String reason = "应采购数:" +detailById.getSkuNum()+";实际采购数:" +skuNum+";差额:"+finalSkuNum+";其他:"+item.getReason();
                        detail.setReason(reason);
                    }
                }
                wareSkuService.addStock(detailById.getSkuId(),detailById.getWareId(),finalSkuNum);
            }else{
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                wareSkuService.addStock(detailById.getSkuId(),detailById.getWareId(),detailById.getSkuNum());
            }

            detail.setId(item.getItemId());

            updates.add(detail);
        }
        purchaseDetailService.updateBatchById(updates);

        //1.改变采购单状态
        Long purchaseId = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        if (isItemAllDone){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else{
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.updateById(purchaseEntity);

        return 0;
    }


}